package com.java.bytecode;

import javassist.*;

public class CycleServiceTests {
    public static void main(String[] args) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException {
        //1.获取一个ClassPool对象
        ClassPool classPool = ClassPool.getDefault();
        //2.获取一个CtClass对象
        CtClass ctClass = classPool.get("com.java.bytecode.CycleService");
        //3.获取一个CtMethod对象
        CtMethod ctMethod = ctClass.getDeclaredMethod("doCycle");
        //4.修改原有目标方法
        ctMethod.insertBefore("{System.out.println(\"start\");}");
        ctMethod.insertAfter("{System.out.println(\"end\");}");
        //5.获取类的字节对象
        Class<?> newClass = ctClass.toClass();
        CycleService cycleService1= (CycleService) newClass.newInstance();
        cycleService1.doCycle();
        CycleService cycleService2=new CycleService();
        cycleService2.doCycle();
    }
}

